<template>
  <div class="appointment-container">
    <!-- 切换月度/每日预约的标签页 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="每月预约" name="monthly"></el-tab-pane>
      <el-tab-pane label="每日预约" name="daily"></el-tab-pane>
    </el-tabs>

    <!-- 每月预约视图 -->
    <div v-show="activeTab === 'monthly'" class="monthly-view">
      <!-- 顶部筛选栏 -->
      <div class="filter-bar">
        <el-date-picker
            v-model="monthSearch.searchMonth"
            type="month"
            placeholder="选择月份"
            format="YYYY年MM月"
            value-format="YYYY年MM月"
            @change="onMonthChange"
        ></el-date-picker>
        <!--            value-format="YYYY-MM"-->
        <el-input
            v-model="monthSearch.storeId"
            placeholder="请输入门店ID"
            clearable
            style="width: 300px; margin: 0 10px"
        ></el-input>

        <el-button type="primary" @click="searchMonthlyAppointments">搜索</el-button>
      </div>

      <!-- 日历头部 -->
      <div class="calendar-header">
        <h3>{{formattedCurrentMonth}}</h3>
        <div class="calendar-actions">
          <el-button  @click="prevMonth">上月</el-button>
          <el-button  @click="nextMonth">下月</el-button>
        </div>
      </div>

      <!-- 日历网格 -->
      <div class="calendar-grid">
        <!-- 星期标题行 -->
        <div class="weekdays">
          <div class="weekday" v-for="day in weekdays" :key="day">{{ day }}</div>
        </div>

        <!-- 日期单元格 -->
        <div class="date-cells">
          <div
              v-for="(dateCell, index) in dateCells"
              :key="index"
              class="date-cell"
              :class="{
              'other-month': dateCell.isOtherMonth,
              'current-date': dateCell.isCurrentDate,
              'has-appointments': dateCell.totalAmount > 0
            }"
              @click="selectDate(dateCell.date,monthSearch.storeId)"
          >
            <div class="date-number">{{ dateCell.day }}</div>
            <div class="appointment-info">
              <span>预约: {{ dateCell.totalAmount !== null ? dateCell.totalAmount : '-' }}</span>
              <span>完成: {{ dateCell.finishedAmount !== null ? dateCell.finishedAmount : '-' }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 每日预约视图 -->
    <div v-show="activeTab === 'daily'" class="daily-view">
      <!-- 顶部筛选栏 -->
      <div class="filter-bar">
        <el-date-picker
            v-model="dateSearch.searchDate"
            type="date"
            placeholder="选择日期"
            format="YYYY年MM月DD日"
            value-format="YYYY-MM-DD"
            @change="onDateChange"
        ></el-date-picker>

        <el-input
            v-model="dateSearch.storeId"
            placeholder="请输入门店ID"
            clearable
            style="width: 300px; margin: 0 10px"
        ></el-input>

        <el-button type="primary" @click="searchDailyAppointments">搜索</el-button>
      </div>

      <!-- 详情标签页 -->
      <el-tabs v-model="detailTab" @tab-click="handleDetailTabClick">
        <el-tab-pane label="号码详情" name="phone"></el-tab-pane>
      </el-tabs>

      <!-- 号码详情 -->
      <div v-show="detailTab === 'phone'" class="phone-details">

        <!-- 号码详情表格（自动渲染两行：已约号 + 剩余号） -->
        <el-table :data="timeSlots" border style="width: 100%">
          <el-table-column label="预约分类" width="120">
            <template #default="scope">
              <div class="cell-content">{{ scope.row.label }}</div>
            </template>
          </el-table-column>

          <!-- 循环时段（与两行数据匹配） -->
          <el-table-column
              v-for="(slot, index) in timeSlots[0].slots"
              :key="index"
              :label="slot.timeRange"
              width="150"
          >
            <template #default="scope">
              <!-- 若为“已约号”行，显示预约列表 -->
              <template v-if="scope.row.label === '已约号'">
                <div class="appointment-cards">
                  <el-card
                      v-for="(appointment, appIndex) in scope.row.slots[index].appointments"
                      :key="appIndex"
                      class="appointment-card"
                  >
                    <div>{{ appointment?.userName??'-' }}</div>
                    <el-button size="mini" type="text" @click="showAppointmentDetails(appointment.appointmentId)">预约详情</el-button>

                  </el-card>
                </div>
              </template>

              <!-- 若为“剩余号”行，显示剩余数量 -->
              <template v-else-if="scope.row.label === '剩余号'">
                <div class="remaining-number">
                  剩余号: {{ scope.row.slots[index].remaining }}
                </div>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>

    </div>

    <!-- 预约详情弹窗 -->
    <el-dialog v-model="appointmentDetailsVisible" title="预约详情">
      <div class="dialog-content">
        <h4>预约商品/服务</h4>
        <el-table :data="appointmentProducts" border>
          <el-table-column type="index" label="序号"></el-table-column>
          <el-table-column prop="itemName" label="商品/服务名称"></el-table-column>
          <el-table-column prop="itemType" label="类型"></el-table-column>
          <el-table-column prop="standardPrice" label="标准价格"></el-table-column>
          <el-table-column prop="retailPrice" label="零售价格"></el-table-column>
          <el-table-column prop="quantity" label="预约数量"></el-table-column>
          <el-table-column prop="totalPrice" label="预约总价"></el-table-column>
        </el-table>

        <h4>预约流程</h4>
        <div class="dialog-content">
          <el-timeline>
            <el-timeline-item
                v-for="(step, index) in processSteps"
                :key="index"
                :type="index === processSteps.length - 1 ? 'success' : 'primary'"
            >
              <div class="process-step">
                <p>{{ formattedTime(step.operationTime) }}</p>
                <h4>{{ step.appointmentStatus }}</h4>
                <p>{{ "顾客："+step.userDto?.userName+"-"+step.userDto?.userPhone }}</p>
                <p>
                  员工：
                  {{ step.staff?.staffName ?? "-" }}-{{ step.staff?.phone ?? "-" }}
                </p>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>

      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="appointmentDetailsVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import {ref, computed, onMounted, reactive} from 'vue'
import {
  ElTabs,
  ElTabPane,
  ElDatePicker,
  ElInput,
  ElButton,
  ElTable,
  ElTableColumn,
  ElCard,
  ElTag,
  ElDialog,
  ElTimeline,
  ElTimelineItem,
  ElMessage, dayjs
} from 'element-plus'
import 'element-plus/dist/index.css'
import axios from "axios";

//时间格式化
const formattedTime = (timeStr) => {
  return dayjs(timeStr).format('YYYY-MM-DD HH:mm:ss');
};


// 状态管理
const monthSearch=reactive({
      "storeId":null,
      "searchMonth":''
})

const dateSearch=reactive({
      "storeId":null,
      "searchDate":''
})


const activeTab = ref('monthly')
const detailTab = ref('phone')
const currentMonth = ref(new Date().toISOString().split('T')[0].substring(0, 7))
const currentDate = ref(new Date().toISOString().split('T')[0])

const appointmentDetailsVisible = ref(false)
const processDetailsVisible = ref(false)

// 计算属性
const formattedCurrentMonth = computed(() => {
  const [year, month] = currentMonth.value.split('-')
  return `${year}年${month}月`
})

// 模拟数据
const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

// 时间槽数据
const timeSlots = ref([
  {
    label: '已约号',
    slots: [
      { timeRange: '8:00-9:00', appointments: [] },
      { timeRange: '9:00-10:00', appointments: [] },
      { timeRange: '10:00-11:00', appointments: [] },
      { timeRange: '11:00-12:00', appointments: [] },
      { timeRange: '14:00-15:00', appointments: [] },
      { timeRange: '15:00-16:00', appointments: [] },
      { timeRange: '16:00-17:00', appointments: [] },
      { timeRange: '17:00-18:00', appointments: [] }
    ]
  },
  {
    label: '剩余号',
    slots: [
      { timeRange: '8:00-9:00',  remaining: 5 },
      { timeRange: '9:00-10:00',  remaining: 5 },
      { timeRange: '10:00-11:00',  remaining: 5 },
      { timeRange: '11:00-12:00', remaining: 5 },
      { timeRange: '14:00-15:00',  remaining: 5 },
      { timeRange: '15:00-16:00',  remaining: 5 },
      { timeRange: '16:00-17:00',  remaining: 5 },
      { timeRange: '17:00-18:00',  remaining: 5 }
    ]
  },
]);




// 预约详情数据
const appointmentProducts = ref([
  {
    "id": 1,
    "appointmentId": 1,
    "itemType": "服务",
    "itemName": "XXX",
    "itemId": 1,
    "quantity": 1,
    "standardPrice": 1,
    "retailPrice": 1,
    "totalPrice": 180
  }
])


// 流程步骤
const processSteps = ref([
  {
    "id": 11,
    "appointmentId": 1,
    "appointmentStatus": "已完成",
    "operationTime": "2025-06-01T10:30:00",
    "userId": 101,
    "userDto": {
      "id": 101,
      "userName": "张三",
      "userPhone": "13800138001"
    },
    "staffId": 401,
    "staff": {
      "id": 401,
      "staffName": "李店长",
      "phone": "13811111111"
    }
  },
])

// 日期单元格数据
const dateCells = ref([

])

// 生成本地时区的YYYY-MM-DD格式日期字符串（避免时区转换问题）
const formatLocalDate = (year, month, day) => {
  // 月份和日期补零（确保两位格式）
  const pad = (num) => num.toString().padStart(2, '0');
  return `${year}-${pad(month)}-${pad(day)}`;
};
const generateCalendar = () => {
  const [year, month] = currentMonth.value.split('-').map(Number); // month是1-12（如6月→6）
  const daysInMonth = new Date(year, month, 0).getDate(); // 当月天数（如6月有30天）
  const firstDay = new Date(year, month - 1, 1); // 月份-1是因为JS Date月份从0开始
  const firstDayWeek = firstDay.getDay();
  const firstDayIndex = firstDayWeek === 0 ? 6 : firstDayWeek - 1;

  const today = new Date();
  const isCurrentMonth = today.getFullYear() === year && today.getMonth() + 1 === month;
  const currentDay = isCurrentMonth ? today.getDate() : null;

  const prevMonthDays = firstDayIndex;
  const prevMonthTotalDays = new Date(year, month - 1, 0).getDate();

  const cells = [];

  // 1. 添加上个月的日期（修复date生成）
  for (let i = prevMonthDays; i > 0; i--) {
    const day = prevMonthTotalDays - i + 1;
    const prevMonth = month - 1 === 0 ? 12 : month - 1; // 上个月（1-12）
    const prevYear = month - 1 === 0 ? year - 1 : year; // 上个月对应的年份
    const date = formatLocalDate(prevYear, prevMonth, day); // 手动拼接本地日期
    cells.push({
      date,
      day,
      totalAmount: null,
      finishedAmount: null,
      isOtherMonth: true,
      isCurrentDate: false
    });
  }

  // 2. 添加当月的日期（修复date生成）
  for (let day = 1; day <= daysInMonth; day++) {
    const date = formatLocalDate(year, month, day); // 当月日期直接用year和month（1-12）
    cells.push({
      date,
      day,
      totalAmount: 0,
      finishedAmount: 0,
      isOtherMonth: false,
      isCurrentDate: isCurrentMonth && day === currentDay
    });
  }

  // 3. 添加下个月的日期（修复date生成）
  const nextMonthFillDays = 7 - (cells.length % 7) || 0;
  for (let day = 1; day <= nextMonthFillDays; day++) {
    const nextMonth = month + 1 === 13 ? 1 : month + 1; // 下个月（1-12）
    const nextYear = month + 1 === 13 ? year + 1 : year; // 下个月对应的年份
    const date = formatLocalDate(nextYear, nextMonth, day); // 手动拼接本地日期
    cells.push({
      date,
      day,
      totalAmount: 0,
      finishedAmount: 0,
      isOtherMonth: true,
      isCurrentDate: false
    });
  }

  dateCells.value = cells;
};


// 生命周期钩子
onMounted(() => {
  generateCalendar()

})


// 日期操作方法
const prevMonth = () => {
  const [year, month] = currentMonth.value.split('-').map(Number)
  const prevMonth = month - 1
  const prevYear = prevMonth === 0 ? year - 1 : year
  const formattedMonth = prevMonth === 0 ? 12 : prevMonth
  currentMonth.value = `${prevYear}-${formattedMonth.toString().padStart(2, '0')}`
  generateCalendar()
  formattedCurrentMonth.value = currentMonth.value;

}

const nextMonth = () => {
  const [year, month] = currentMonth.value.split('-').map(Number)
  const nextMonth = month + 1
  const nextYear = nextMonth === 13 ? year + 1 : year
  const formattedMonth = nextMonth === 13 ? 1 : nextMonth
  currentMonth.value = `${nextYear}-${formattedMonth.toString().padStart(2, '0')}`
  generateCalendar()
  formattedCurrentMonth.value = currentMonth.value;
}

const selectDate = (date,storeId) => {
  if(storeId==null && storeId<=0){
    alert("请先输入门店ID!")
    return;
  }
  dateSearch.searchDate = date;
  dateSearch.storeId = storeId;
  searchDailyAppointments()
  activeTab.value = 'daily'
}

// 搜索方法
const searchMonthlyAppointments = () => {
  axios.post(`/carcenter-service-order/appointment-master/getMonthAppointmentByMonthSearch`, monthSearch)
      .then(resp => {
        const backendData = resp.data.data; // 后端返回的日期数据
        updateDateCellsWithBackendData(backendData); // 自定义方法：将后端数据整合到前端日历
      })
      .catch(err => {
        ElMessage.error(err.response.data);
      });
};

// 将后端数据整合到前端日历的方法
const updateDateCellsWithBackendData = (backendData) => {
  // 创建一个后端数据的映射，以便快速查找
  const backendDataMap = new Map();
  backendData.forEach(item => {
    backendDataMap.set(item.date, item); // 键为日期字符串（如"2025-06-01"）
  });

  // 更新前端的dateCells，合并后端数据
  dateCells.value = dateCells.value.map(cell => {
    const backendItem = backendDataMap.get(cell.date);
    if (backendItem) {
      // 如果后端有该日期的数据，合并totalAmount和finishedAmount
      return {
        ...cell,
        totalAmount: backendItem.totalAmount,
        finishedAmount: backendItem.finishedAmount
      };
    }
    // 否则保持前端原有数据（如上个月/下个月的日期）
    return cell;
  });
};

const searchDailyAppointments = () => {

  axios.post(`/carcenter-service-order/appointment-master/getDayAppointmentByDateSearch`,dateSearch).then(resp => {
    const hourDataList = resp.data.data;
    for (let slot of timeSlots.value[0].slots) {
      for (let hourData of hourDataList) {
        if(slot.timeRange==hourData.timeRange){
          slot.appointments=hourData.masterVos;
        }
      }
    }
    for (let slot of timeSlots.value[1].slots) {
      for (let hourData of hourDataList) {
        if(slot.timeRange==hourData.timeRange){
          slot.remaining=hourData.remaining;
        }
      }
    }

  })

}


// 弹窗方法
const showAppointmentDetails = (appointmentId) => {

// 获取商品和服务列表
  axios.get(`/carcenter-service-order/appointment-detail/getProductServiceListByAppointmentId/${appointmentId}`)
      .then(resp => {
        // 检查响应结构是否符合预期
        if (!resp.data || !Array.isArray(resp.data.data)) {
          console.error('Invalid response structure:', resp);
          return;
        }

        appointmentProducts.value = resp.data.data.map(item => {
          const isService = item.itemType === '服务';
          const dto = isService ? item.serviceDto : item.productDto;

          // 安全获取嵌套属性，防止空指针异常
          const itemName = dto?.serviceName || dto?.productName || '';
          const standardPrice = dto?.standardPrice || 0;
          const retailPrice = dto?.retailPrice || 0;

          return {
            id: item.id,
            appointmentId: item.appointmentId,
            itemId: item.itemId,
            itemName,
            itemType: item.itemType,
            standardPrice,
            retailPrice,
            quantity: item.quantity || 0,
            totalPrice: item.totalPrice || 0
          };
        });
      })
      .catch(error => {
        console.error('Failed to fetch product/service list:', error);
        // 可以在这里添加错误提示逻辑
      });


  //获取预约流程
// 获取预约流程
  axios.get(`/carcenter-service-order/appointment-process/getAppointmentProcessListByAppointmentId/${appointmentId}`)
      .then(resp => {
        const rawList = resp.data.data || []; // 确保数据是数组，避免排序报错

        // 按 operationTime 升序排序（从早到晚）
        const sortedList = rawList.sort((a, b) => {
          // 用 dayjs 解析时间，转为时间戳（毫秒数）进行比较
          const timeA = dayjs(a.operationTime).valueOf();
          const timeB = dayjs(b.operationTime).valueOf();
          return timeA - timeB; // 升序：时间小的排前面
        });

        processSteps.value = sortedList; // 赋值排序后的数组
      })
      .catch(error => {
        console.error('获取流程数据失败：', error);
        processSteps.value = [];
      });


  appointmentDetailsVisible.value = true
}


const onMonthChange = (val) => {
  if (val) {
    // 将"YYYY年MM月"转换为"YYYY-MM"（例如"2025年07月"→"2025-07"）
    const year = val.slice(0, 4);
    const month = val.slice(5, 7); // 截取"MM"部分（确保两位）
    currentMonth.value = `${year}-${month}`;
    generateCalendar(); // 重新生成对应月份的日历
    formattedCurrentMonth.value = currentMonth.value;
  } else {
    // 若清空选择，恢复为当前月
    currentMonth.value = new Date().toISOString().split('T')[0].substring(0, 7);
    generateCalendar();
    formattedCurrentMonth.value = currentMonth.value;

  }
};

const onDateChange = (val) => {
  console.log('日期变更:', val)
}
</script>

<style scoped>
.appointment-container {
  padding: 20px;
}

.filter-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.calendar-actions {
  display: flex;
  gap: 10px;
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 5px;
  margin-bottom: 5px;
}

.weekday {
  text-align: center;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.date-cells {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 5px;
}

.date-cell {
  aspect-ratio: 1/1;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 5px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.date-cell.other-month {
  opacity: 0.5;
}

.date-cell.current-date {
  background-color: #e6f7ff;
  border-color: #1890ff;
}

.date-cell.has-appointments {
  background-color: #f0f9eb;
}

.date-number {
  font-weight: bold;
}

.appointment-info {
  font-size: 12px;
  color: #606266;
}

.appointment-cards, .product-cards, .service-cards {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-bottom: 5px;
}

.appointment-card, .product-card, .service-card {
  width: 100%;
  padding: 5px;
  margin-bottom: 5px;
}

.remaining-number {
  font-size: 12px;
  color: #909399;
}

.cell-header {
  font-weight: bold;
}

.dialog-content {
  padding: 20px;
}

.process-step {
  padding: 10px;
  border-radius: 4px;
  background-color: #f5f7fa;
}
</style>